package com.sicilin.object.affiliated.company.service;

import com.sicilin.common.exception.BusinessException;
import com.sicilin.common.exception.ServiceException;
import com.sicilin.dao.CompanyDao;
import com.sicilin.object.affiliated.company.dto.Company;
import com.sicilin.object.service.ObjectService;
import com.sicilin.po.TCCompany;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional(readOnly = true)
public class CompanyService {

    @Autowired(required = false)
    private CompanyDao companyDao;

    @Autowired
    private ObjectService objectService;

    @Transactional(rollbackFor = {Exception.class})
    public int saveCompany(Company company) throws ServiceException,BusinessException{
        if(!this.validateSaveCompany(company)){
            throw new ServiceException("Invalid company!");
        }
//        if(objectService.isExistObjectCode(company.getCompanyCode(),company.getpCompanyid())){
//            throw new BusinessException("已存在文件夹编码或者公司编码");
//        }
//        TCObject object = objectService.saveObjectSonType(company.getCompanyCode(),company.getCompanyName(),company.getParentId(),1,company.getpCompanyid(), ObjectTypeEnum.SON);
//        TCCompany saveCompany = new TCCompany();
//        company.setCompanyid(object.getObjectId());
//        BeanUtils.copyProperties(company,saveCompany);


        TCCompany saveCompany = new TCCompany();
        BeanUtils.copyProperties(company,saveCompany);
        companyDao.saveOrUpdateCompany(saveCompany);
        return saveCompany.getCompanyId();
    }

    private boolean validateSaveCompany(Company company)throws ServiceException,BusinessException{
        if(company == null){return false;}
        if(company.getCompanyId() == null || company.getCompanyId() == 0){
            return false;
        }
        if(StringUtils.isBlank(company.getCompanyCode())){return false;}
        if(StringUtils.isBlank(company.getCompanyName())){return false;}
        if(company.getpCompanyId() == null){return false;}
        if(company.getCompanyType() == null){return false;}

        return true;
    }

    public Company getCompanyById(int companyId,int pCompanyId) throws ServiceException{
        return companyDao.getCompanyByid(companyId,pCompanyId);
    }

}
